package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.SellBean;
import com.project.bean.ShopBean;
import com.project.mapper.ISellInfoMapper;
import com.project.mapper.ISellMapper;
import com.project.service.ISellService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Map;

/**
 * 销售业务接口实现类
 */
@Service
@Transactional
public class SellServiceImpl implements ISellService {
    @Autowired
    private ISellMapper sellMapper;
    @Autowired
    private ISellInfoMapper sellInfoMapper;
    @Override
    public void outRespository(SellBean sell, Map<String, ShopBean> sellMap) {
        //将订单总价封装到销售对象中
        sell.setMoney(this.computPrice(sellMap));
        //完成销售信息添加
        sellMapper.insert(sell);

        //批量添加销售明细，修改库存
        sellMapper.addSellInfo(sell.getId(),sellMap.values());
        //清空销售车
        sellMap.clear();
    }

    @Override
    public IPage<SellBean> findByItem(Integer pageNO, LocalDate startDate, LocalDate endDate) {
        QueryWrapper<SellBean> qw = new QueryWrapper<>();
        if(startDate != null) {
            qw.ge("s_sellDate", startDate);
        }
        if(endDate != null) {
            qw.le("s_sellDate", endDate);
        }

        return sellMapper.selectPage(new Page(pageNO,3),qw);
    }

    @Override
    public SellBean findById(Integer id) {
        SellBean sellBean = sellMapper.selectById(id);
        sellBean.setSellInfoList(sellInfoMapper.findBySell(id));
        return sellBean;
    }



    /**
     * 计算销售车总价
     * @param sellMap 销售车集合
     * @return 销售车总价
     */
    private int computPrice(Map<String,ShopBean> sellMap){
        int totalPrice = 0;
        for(ShopBean shopBean : sellMap.values()){
            totalPrice += shopBean.getPrice() * shopBean.getNumber();
        }

        return totalPrice;
    }
}
